using System.Collections.Generic;
using UnityEngine;

namespace SimpleCore
{
    /// <summary>
    /// 获取协程等待对象，避免重复创建.
    /// waitUntil之类的不打算加。因为涉及到Func的引用问题，及其容易导致内存泄漏。
    /// </summary>
    public class YieldTool
    {
        public static void Dispose()
        {
            _waitForMap.Clear();
            _waitForFixedUpdate = null;
            _waitForEndOfFrame = null;
        }

        public static WaitForFixedUpdate WaitForFixedUpdate
        {
            get
            {
                if (_waitForFixedUpdate == null)
                {
                    _waitForFixedUpdate = new WaitForFixedUpdate();
                }

                return _waitForFixedUpdate;
            }
        }

        public static WaitForEndOfFrame WaitForEndOfFrame
        {
            get
            {
                if (_waitForEndOfFrame == null)
                {
                    _waitForEndOfFrame = new WaitForEndOfFrame();
                }

                return _waitForEndOfFrame;
            }
        }

        public static WaitForSeconds WaitForSeconds(float duration)
        {
            if (!_waitForMap.TryGetValue(duration, out var data))
            {
                data = new WaitForSeconds(duration);
                _waitForMap.Add(duration, data);
            }
            
            return data;
        }
        
        private static WaitForFixedUpdate _waitForFixedUpdate;
        private static WaitForEndOfFrame _waitForEndOfFrame;
        private static Dictionary<float, WaitForSeconds> _waitForMap = new Dictionary<float, WaitForSeconds>();
    }
}